var app = {
    format:function(str){
        return str > 9 ? str + "" : "0" + str;
    },
    init:function(){
        this.param = {
            stationName:"",
            province:"",
            city:"",
            county:""
        };
        this.points = [];
        this.getStationList(this.param);
        this.initForm();
        this.bindEvent();
        this.initMap();
    },
    initForm:function(){
        var that = this;
        layui.use('form', function(){
            var form = layui.form;
            var provinces = common.getProvinces();
            $("[name=province]").empty().append(template("select-option",{list:provinces}));
            form.render('select'); //刷新select选择框渲染
            form.on('select(province)', function(data){
                that.param.province = data.value;
                var cities = common.getCities(data.value);
                $("[name=city]").empty().append(template("select-option",{list:cities}));
                form.render('select'); //刷新select选择框渲染
              }); 
            form.on('select(city)', function(data){
                that.param.city = data.value;
                var zones = common.getZone(that.param.province,that.param.city);
                $("[name=zone]").empty().append(template("select-option",{list:zones}));
                form.render('select'); //刷新select选择框渲染
            }); 
            form.on('select(zone)', function(data){
                that.param.county = data.value;
            }); 
          });
    },
    bindEvent:function(){
        var that = this;
        $(document).on("click",".search",function(e){
            that.param.stationName = $(".station-name").val();
            that.getStationList(that.param);
            e.preventDefault();
            e.stopPropagation();
        })
        $(document).on("click",".export",function(e){
            layer.confirm('您会导出' + that.total  +'条记录，需要等待较长时间，是否确定导出？', {
                btn: ['确定','取消'] //按钮
              }, function(){
                that.exportExcel();
              }, function(){
                
              });
            e.preventDefault();
            e.stopPropagation();
        })
    },
    exportExcel:function(){
        var that = this;
        that.loading = layer.load(0, {
            shade: [0.1,'#fff'] //0.1透明度的白色背景
        });
        var type = $('input[name=type]:checked').val();
        
        if(that.param) {
            that.param.type = type;
        } else {
            that.param = {
                type: type,
            }
        }
        that.param.stationName = $(".station-name").val();
        $.ajax({
            url:'/api/v1/meteorology/station/exportTemp',
            type:'post',
            data:this.param,
            success:function(res){
                layer.close(that.loading);
                if(res.errcode == "0000"){
                    layer.msg("导出成功",{icon: 1});
                    window.open(res.data.exportPath); 
                }else{
                    layer.msg(res.errmsg,{icon: 0});
                }
            },
            error:function(){

            }
        });
    },
    initMap:function(){
        var map = new BMap.Map("container",{minZoom:5,maxZoom:8});
        // 创建地图实例  
        var point = new BMap.Point(116.404, 39.915);
        // 创建点坐标  
        map.centerAndZoom(new BMap.Point(105.000, 38.000), 6);
        //map.centerAndZoom(point, 15);
        // 初始化地图，设置中心点坐标和地图级别
        map.enableScrollWheelZoom(true);
        this.map = map;
    },
    addPoints:function(paramPoints){
        var that = this;
        if (document.createElement('canvas').getContext) {  // 判断当前浏览器是否支持绘制海量点
            this.map.clearOverlays();
            var points = [];  // 添加海量点数据
            for (var i = 0; i < paramPoints.length; i++) {
              points.push(new BMap.Point(parseInt(paramPoints[i].longitude,10)/100, parseInt(paramPoints[i].latitude,10)/100));
              paramPoints[i].compareLongitude = parseInt(paramPoints[i].longitude,10)/100;
              paramPoints[i].compareLatitude = parseInt(paramPoints[i].latitude,10)/100;
            }
            that.points = paramPoints;
            var options = {
                size: BMAP_POINT_SIZE_NORMAL,
                shape: BMAP_POINT_SHAPE_STAR,
                color: '#800080'
            }
            var pointCollection = new BMap.PointCollection(points, options);  // 初始化PointCollection
            pointCollection.addEventListener('click', function (e) {
              //alert('单击点的坐标为：' + e.point.lng + ',' + e.point.lat);  // 监听点击事件
              that.filterPoints(e.point);
            });
            // 鼠标经过时
            pointCollection.addEventListener("mouseover", function(e) {   
                var opts = {
                    position : e.point,    // 指定文本标注所在的地理位置
                    offset   : new BMap.Size(10, -10)    //设置文本偏移量
                }
                var station = that.filterPoint(e.point);
                if(that.label){
                    that.map.removeOverlay(that.label);
                }
                that.label = new BMap.Label("台站名:"+ station.name, opts);  // 创建文本标注对象
                that.label.setStyle({
                    color:"#000",
                    fontSize:"16px;",
                    padding:"8px",
                    borderRadius:"5px",
                    borderColor:"#998dd5"
                });
                that.map.addOverlay(that.label);   
            });
            // 鼠标离开时
            pointCollection.addEventListener("mouseout", function(e) {
                that.map.removeOverlay(that.label);
            });
            that.map.addOverlay(pointCollection);  // 添加Overlay
        } else {
            alert('请在chrome、safari、IE8+以上浏览器查看本示例');
        }
    },
    getStationList:function(param){
        var that = this;
        if(param.stationName.length > 4){
            layer.msg("台站名称不超过4个字符！",{icon: 0});
            return;
        }
        var type = $('input[name=type]:checked').val();
        param.type = type;
        $.ajax({
            url:'/api/v1/meteorology/station/list',
            type:'post',
            data:param,
            success:function(res){
                if(res.errcode == "0000"){
                    //that.renderTable(res.data)
                    that.addPoints(res.data);
                }else{

                }
            },
            error:function(){

            }
        });
    },
    getDetail:function(point,date){
        var that = this;
        var param = {};
        param.station = point.station;
        param.startDate = date.getFullYear() + "-01-01";
        param.endDate = date.getFullYear() + "-12-31";
        this.detailParam = {
            stationName:point.name,
            startDate:param.startDate,
            endDate:param.endDate
        }
        var type = $('input[name=type]:checked').val();
        param.type = type;
        $.ajax({
            url:'/api/v1/meteorology/station/getStationTemp',
            type:'post',
            data:param,
            success:function(res){
                if(res.errcode == "0000"){
                    if(res.data){
                        $(".dialog-wrap .export").attr("disabled",false);
                        that.total = res.data.length;
                        var filterData = that.tidyData(res.data);
                        that.filterData = filterData;
                        that.initTemperature(filterData);
                    }else{
                        $(".dialog-wrap .export").attr("disabled",true);
                        that.total = 0;
                        var filterData = that.tidyData("");
                        that.filterData = filterData;
                        that.initTemperature(filterData);
                        layer.msg("暂无该台站气象数据",{icon: 0});
                    }
                }else{

                }
            },
            error:function(){

            }
        });
        $.ajax({
            url:'/api/v1/meteorology/station/getStationInfo',
            type:'post',
            data:{station:point.station},
            success:function(res){
                if(res.errcode == "0000"){
                    if(res.data){
                        that.introduce = res.data;
                    }else{
                        //layer.msg("暂无数据,请选择其他年份",{icon: 0});
                    }
                }else{

                }
            },
            error:function(){

            }
        });
    },
    tidyData:function(data){
        var averageT = [];
        var maxT = [];
        var minT = [];
        var rain  = [];
        var averageTObj = {};
        var maxTObj = {};
        var minTObj = {};
        var rainObj = {};
        if(data){
            for(var i = 1;i < 13; i++){
                for(var j = 0;j < data.length; j++){
                    if(i == data[j].month){
                        if(averageTObj[i+""] == undefined){
                            averageTObj[i+""] = [];
                            averageTObj[i+""].push(data[j].averageTemperature);
                        }else{
                            averageTObj[i+""].push(data[j].averageTemperature);
                        }
                        if(maxTObj[i+""] == undefined){
                            maxTObj[i+""] = [];
                            maxTObj[i+""].push(data[j].max);
                        }else{
                            maxTObj[i+""].push(data[j].max);
                        }
                        if(minTObj[i+""] == undefined){
                            minTObj[i+""] = [];
                            minTObj[i+""].push(data[j].min);
                        }else{
                            minTObj[i+""].push(data[j].min);
                        }if(rainObj[i+""] == undefined){
                            rainObj[i+""] = [];
                            rainObj[i+""].push(data[j].rain);
                        }else{
                            rainObj[i+""].push(data[j].rain);
                        }
                    }
                }
            }
            for(var k in averageTObj){
                var avgSum = 0;
                for(var s = 0;s < averageTObj[k].length;s++){
                    avgSum +=  averageTObj[k][s];
                }
                averageTObj[k] = parseInt(avgSum/averageTObj[k].length,10);
                averageT.push(averageTObj[k]);
            }
            for(var k in maxTObj){
                var avgSum = 0;
                for(var s = 0;s < maxTObj[k].length;s++){
                    avgSum +=  maxTObj[k][s];
                }
                maxTObj[k] = parseInt(avgSum/maxTObj[k].length,10);
                maxT.push(maxTObj[k]);
            }
            for(var k in minTObj){
                var avgSum = 0;
                for(var s = 0;s < minTObj[k].length;s++){
                    avgSum +=  minTObj[k][s];
                }
                minTObj[k] = parseInt(avgSum/minTObj[k].length,10);
                minT.push(minTObj[k]);
            }
            for(var k in rainObj){
                var avgSum = 0;
                for(var s = 0;s < rainObj[k].length;s++){
                    avgSum +=  rainObj[k][s];
                }
                rainObj[k] = parseInt(avgSum/rainObj[k].length,10);
                rain.push(rainObj[k]);
            }
        }
        return {
            avgT:averageT,
            maxT:maxT,
            minT:minT,
            rain:rain
        }
    },
    initRain:function(data){
        var option = {
            tooltip: {
                trigger: 'axis'
            },
            legend: {
                data:['降水量']
            },
            toolbox: {
                show: false
            },
            xAxis:  {
                type: 'category',
                boundaryGap: false,
                data: ['01','02','03','04','05','06','07','08','09','10','11','12']
            },
            yAxis: {
                type: 'value',
                axisLabel: {
                    formatter: '{value}mm'
                }
            },
            grid:{
                left:80
            },
            series: [
                {
                    name:'降水量',
                    type:'line',
                    data:data.rain,
                    smooth: true,
                    itemStyle : {
                        normal : {
                            lineStyle:{
                                color:'#7dc8ff'
                            }
                        }
                    }
                }
            ]
        };
        var chart = echarts.init(document.getElementById('rain'))
        chart.setOption(option);
    },
    initTemperature:function(data){
        var option = {
            tooltip: {
                trigger: 'axis'
            },
            legend: {
                data:['最高气温','最低气温','平均气温']
            },
            toolbox: {
                show: false
            },
            xAxis:  {
                type: 'category',
                boundaryGap: false,
                data: ['01','02','03','04','05','06','07','08','09','10','11','12']
            },
            yAxis: {
                type: 'value',
                axisLabel: {
                    formatter: '{value} °C'
                }
            },
            series: [
                {
                    name:'最高气温',
                    type:'line',
                    data:data.maxT,
                    smooth: true,
                    itemStyle : {
                        normal : {
                            lineStyle:{
                                color:'#ff3b7b'
                            }
                        }
                    }
                },
                {
                    name:'最低气温',
                    type:'line',
                    data:data.minT,
                    smooth: true,
                    itemStyle : {
                        normal : {
                            lineStyle:{
                                color:'#7dc8ff'
                            }
                        }
                    }
                },
                {
                    name:'平均气温',
                    type:'line',
                    data:data.avgT,
                    smooth: true,
                    itemStyle : {
                        normal : {
                            lineStyle:{
                                color:'#998ed3'
                            }
                        }
                    }
                }
            ]
        };
        var chart = echarts.init(document.getElementById('temperature'))
        chart.setOption(option);
    },
    filterPoint:function(point){
        var target = null;
        var that = this;
        for(var i = 0;i<this.points.length;i++){
            if(point.lng == this.points[i].compareLongitude && point.lat == this.points[i].compareLatitude){
                target = this.points[i];
                break;
            }
        }
        if(target){
            return target;
        }
    },
    filterPoints:function(point){
        var target = null;
        var that = this;
        for(var i = 0;i<this.points.length;i++){
            if(point.lng == this.points[i].compareLongitude && point.lat == this.points[i].compareLatitude){
                target = this.points[i];
                break;
            }
        }
        if(target){
            that.introduce = [];
            that.filterData = {};
            that.layerIndex = layer.open({
                type: 1,
                title: "台站名称&nbsp;<span>(" + target.name+ ")</span>",
                closeBtn: 1,
                shadeClose:false,
                content: template("dialog-wrap",{}),
                btn: ['关闭'],
                area: ['600px', '510px']
                ,yes: function(index, layero){
                  //按钮【按钮一】的回调
                  layer.closeAll();
                },
                success:function(){
                    layui.use('element', function(){
                        var element = layui.element;
                        //一些事件监听
                        element.on('tab(docDemoTabBrief)', function(data){
                            if(data.index == 1){
                                that.initRain(that.filterData);
                            }else if(data.index == 2){
                                //station-introduce
                                $("#introduce").empty().append(template("station-introduce",that.introduce));
                            }
                        });
                    });
                    that.getDetail(target,new Date());
                    layui.use('laydate', function(){
                        var laydate = layui.laydate;
                        //执行一个laydate实例
                        laydate.render({
                            elem: '#year', //指定元素,
                            type:"year",
                            min:"100-1-1",
                            value:new Date().getFullYear(),
                            done: function(value, date){
                                that.getDetail(target,new Date(value));
                            }
                        });
                    });
                }
            });
            
        }else{
            console.log("未匹配到台站");
        }
    }
}

app.init();